<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
App::uses('Sanitize', 'Utility');
/**
 * Articles Controller
 *
 * @property Article $Article
 */
class ArticlesController extends AppController {
	
	public $helpers = array('Cksource','FileUpload.FileUpload');
	public $components = array('FileUpload.FileUpload');
	
	public function beforeFilter(){
		parent::beforeFilter();
		$this->FileUpload->uploadDir('files'.DS.'upload'.DS.'images');
	}

/**
 * index method
 *
 * @return void
 */
	public function index() {
		$options = array();
		if ($this->request->is('post')) {
			if(isset($this->request->data['Article']['domain_id']) && $this->request->data['Article']['domain_id']!= ""){
				$options['conditions']['Article.domain_id'] = $this->request->data['Article']['domain_id'];
				$this->passedArgs['domain_id'] = $this->request->data['Article']['domain_id'];
			}
			if(isset($this->request->data['Article']['status']) && $this->request->data['Article']['status'] !=''){
				$options['conditions']['Article.status'] = $this->request->data['Article']['status'];
				$this->passedArgs['status'] = $this->request->data['Article']['status'];
			}
			$this->paginate = $options;
		}else{
			if(isset($this->passedArgs['domain_id']) && $this->passedArgs['domain_id']!= "") $options['conditions']['Article.domain_id'] = $this->passedArgs['domain_id'];
			if(isset($this->passedArgs['status']) && $this->passedArgs['status'] !='') $options['conditions']['Article.status'] = $this->passedArgs['status'];
			$this->paginate = $options;				
		}
		
		$this->Article->recursive = 0;
		$articles = $this->paginate();
		$this->loadModel('Domain');
		$domains = $this->Domain->find('list');
		$this->set(compact('articles','domains'));
	}

/**
 * view method
 *
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		$this->Article->id = $id;
		if (!$this->Article->exists()) {
			throw new NotFoundException(__('Invalid article'));
		}
		
		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])){
		// dodajemy do domeny
			$this->Article->Domain->id = $this->passedArgs['d'];
			if ($this->Article->Domain->exists()) {
				$data['Article']['domain_id'] = $this->passedArgs['d'];
				$this->request->data = $data;
			}
		}
		$this->loadModel('RatingGroup');
		$doamins = $this->Article->Domain->find('list');
		$users = $this->Article->User->find('list');
		$rating_groups = $this->RatingGroup->find('list');
		$article = $this->Article->read(null, $id);
		
		$this->set(compact('article', 'rating_groups','doamins','users'));
	}

/**
 * add method
 *
 * @return void
 */
	public function add() {
		if ($this->request->is('post')) {
			$this->request->data['Article']['user_id'] = $this->Session->read('Auth.User.id');
			$this->request->data['Article']['slug'] = strtolower( Inflector::slug($this->request->data['Article']['name'],'-') );
			$this->Article->create();
			if ($this->Article->save($this->request->data)) {
				$this->Session->setFlash(__('The article has been saved'));
				if(isset($this->request->data['Article']['submit_and_add_new']) && $this->request->data['Article']['submit_and_add_new'] == true ){
					if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'articles','action' =>'add','d'=>$this->passedArgs['d']));
				}
				if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'domains','action' =>'view',$this->passedArgs['d'],'d'=>'articles'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The article could not be saved. Please, try again.'));
			}
		}
		
		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])){
			// dodajemy do domeny
			$this->Article->Domain->id = $this->passedArgs['d'];
			if ($this->Article->Domain->exists()) {
				$data['Article']['domain_id'] = $this->passedArgs['d'];
				$this->request->data = $data;
			}else{
				$this->Session->setFlash(__('The article could not be saved. Please, select first domain'));
				$this->redirect($this->referer());
			}
		

			$options['joins'] = array(
				array('table' => 'domains_menuses',
					        'alias' => 'DomainsMenus',
					        'type' => 'inner',
					        'conditions' => array(
					            'Menus.id = DomainsMenus.menus_id'
				)
			),
				array('table' => 'domains',
					        'alias' => 'Domain',
					        'type' => 'inner',
					        'conditions' => array(
					            'DomainsMenus.domain_id = Domain.id'
							)
				)
			);
			$options['conditions'] = array(
					    'Domain.id' => $this->passedArgs['d']
			);
			$options['order'] = array(
							    'Menus.lft'
			);
			
			$this->loadModel('Menus');
			$menuses = $this->Menus->find('threaded',$options);
			$menuses = $this->treeForCombobox($menuses,'Menus',array('model'=>'Menus','name'=>'name'),false);
			
			$ratings_ = $this->Article->Rating->find('all');
			$ratings = array();
			foreach ($ratings_ as $key => $rating) {
				$ratings[$rating['RatingGroup']['name']][$rating['Rating']['id']] = $rating['Rating']['name'] ;
			}
	
			$this->set(compact('menuses','ratings'));
		}else{
			$this->Session->setFlash(__('The article could not be saved. Please, select first domain'));
			$this->redirect($this->referer());
		}
	}
	
	

/**
 * edit method
 *
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		$this->Article->id = $id;
		if (!$this->Article->exists()) {
			throw new NotFoundException(__('Invalid article'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			$this->request->data['Article']['user_id'] = $this->Session->read('Auth.User.id');
			$this->request->data['Article']['slug'] = strtolower( Inflector::slug($this->request->data['Article']['name'],'-') );
			if ($this->Article->save($this->request->data)) {
				$this->Session->setFlash(__('The article has been saved'));
				if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'domains','action' =>'view',$this->passedArgs['d'],'d'=>'articles'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The article could not be saved. Please, try again.'));
			}
		} else {			
			$this->request->data = $this->Article->read(null, $id);
		}		

		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])){
			// dodajemy do domeny
			$this->Article->Domain->id = $this->passedArgs['d'];
			if ($this->Article->Domain->exists()) {
				$this->request->data['Article']['domain_id'] = $this->passedArgs['d'];
			}
		}
				
		$options['joins'] = array(
			array('table' => 'domains_menuses',
				        'alias' => 'DomainsMenus',
				        'type' => 'inner',
				        'conditions' => array(
				            'Menus.id = DomainsMenus.menus_id'
						)
			),
			array('table' => 'domains',
				        'alias' => 'Domain',
				        'type' => 'inner',
				        'conditions' => array(
				            'DomainsMenus.domain_id = Domain.id'
						)
			)
		);
		
		$options['conditions'] = array(
				    'Domain.id' => (isset($this->passedArgs['d'])) ? $this->passedArgs['d'] : $this->request->data['Article']['domain_id']
		);
		
		$this->Article->Menus->recursive = 1;
		$menuses = $this->Article->Menus->find('threaded',$options);	
		
// 		foreach ($menuses as $key1 => $menu) {
// 			if(isset($menu['Submenu']) && is_array($menu['Submenu']) && !empty($menu['Submenu'])){
// 				foreach ($menu['Submenu'] as $key2 => $submenu) {
// 					$menuses[$key1]['children'][count($menuses[$key1]['children'])] = array('Menus'=>array('id'=>$submenu['id'],'parent_id'=>$menu['Menus']['id'],'name'=>$submenu['name']));
// 				}
// 			}
// 		}
		$menuses = $this->treeForCombobox($menuses,'Menus',array('model'=>'Menus','name'=>'name'),false);
// 		$menuses = $this->Article->Menus->find('list');
		
		$options['joins'] = array(
			array('table' => 'menuses_submenus',
			        'alias' => 'MenusesSubmenu',
			        'type' => 'inner',
			        'conditions' => array(
			            'Submenu.id = MenusesSubmenu.submenu_id'
					)
			),
			array('table' => 'menuses',
				'alias' => 'Menus',
				'type' => 'inner',
					'conditions' => array(
						'MenusesSubmenu.menus_id = Menus.id'
					)
			),
			array('table' => 'domains_menuses',
			        'alias' => 'DomainsMenus',
			        'type' => 'inner',
			        'conditions' => array(
			            'Menus.id = DomainsMenus.menus_id'
					)
			),
			array('table' => 'domains',
			        'alias' => 'Domain',
			        'type' => 'inner',
			        'conditions' => array(
			            'DomainsMenus.domain_id = Domain.id'
					)
			),
			
		);
		
		$options['conditions'] = array(
						    'Domain.id' => (isset($this->passedArgs['d'])) ? $this->passedArgs['d'] : $this->request->data['Article']['domain_id']
		);

		$this->Article->Submenu->recursive = 1;
		$submenuses = $this->Article->Submenu->find('threaded',$options);
		$submenus = $this->treeForCombobox($submenuses,'Submenu',array('model'=>'Submenu','name'=>'name'),false);
		$domains = $this->Article->Domain->find('list');
		$ratings_ = $this->Article->Rating->find('all');
		$ratings = array();
		foreach ($ratings_ as $key => $rating) {
			$ratings[$rating['RatingGroup']['name']][$rating['Rating']['id']] = $rating['Rating']['name'] ;
		}
		$this->set(compact('menuses', 'domains','submenus','ratings'));
	}
	
	
	public function edit_rating($id=null){
		$this->Article->id = $id;
		if (!$this->Article->exists()) {
			throw new NotFoundException(__('Invalid article'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			$this->request->data['Article']['user_id'] = $this->Session->read('Auth.User.id');
			$this->request->data['Article']['slug'] = strtolower( Inflector::slug($this->request->data['Article']['name'],'-') );
			if ($this->Article->save($this->request->data)) {
				$this->Session->setFlash(__('The article has been saved'));
				$this->redirect(array('controller'=>'articles','action' =>'view',$id));				
			} else {
				$this->Session->setFlash(__('The article could not be saved. Please, try again.'));
			}
		} else {
			$this->request->data = $this->Article->read(null, $id);
			$ratings_ = $this->Article->Rating->find('all');
			$ratings = array();
			foreach ($ratings_ as $key => $rating) {
				$ratings[$rating['RatingGroup']['name']][$rating['Rating']['id']] = $rating['Rating']['name'] ;
			}
			$this->set(compact('ratings'));
		}		
	}	
	
	public function send($id = null) {
		$this->Article->id = $id;
		if (!$this->Article->exists()) {
			throw new NotFoundException(__('Invalid article'));
		}
		
		$users = $this->Article->User->find('list');
		$domains = $this->Article->Domain->find('list');
		$this->set(compact('users', 'domains'));
		
		if ($this->request->is('post') || $this->request->is('put')) {
// 			debug($this->request->data); die;
			$this->Article->User->id = $this->request->data['Article']['User'];
			$user_email = $this->Article->User->field('email');
			
			$email = new CakeEmail();
			$email->config('gmail');
			$email->log = true;
			
			$email->from(array($this->Session->read('Auth.User.email') => 'SEOsolution'));
			$email->to($user_email);
			$email->subject('Article at : '.$domains[$this->request->data['Article']['domain_id']]);
			$content = __("Save at url: ",true).'http://'.$domains[$this->request->data['Article']['domain_id']]."\n\r";
			$content .= __("Title: ",true).$this->request->data['Article']['name']."\n\r";
			$content .= Sanitize::html( __("Content: ",true).$this->request->data['Article']['content'],array('remove'=>true))."\n\r";
			$content .= __("Keywords: ",true).$this->request->data['Article']['keywords']."\n\r";
			$content .= __("Description: ",true).$this->request->data['Article']['descriptions']."\n\r";			
			$email->send($content);
			
			$this->Session->setFlash(__('Article sended'));			
			if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'domains','action' =>'view',$this->passedArgs['d'],'d'=>'articles'));
		} else {
			$this->request->data = $this->Article->read(null, $id);
		}
	
		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])){
			// dodajemy do domeny
			$this->Article->Domain->id = $this->passedArgs['d'];
			if ($this->Article->Domain->exists()) {
				$this->request->data['Article']['domain_id'] = $this->passedArgs['d'];
			}
		}
	

		
	}

/**
 * delete method
 *
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->Article->id = $id;
		if (!$this->Article->exists()) {
			throw new NotFoundException(__('Invalid article'));
		}
		if ($this->Article->delete()) {
			$this->Session->setFlash(__('Article deleted'));
			if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'domains','action' =>'view',$this->passedArgs['d'],'d'=>'articles'));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('Article was not deleted'));
		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'domains','action' =>'view',$this->passedArgs['d'],'d'=>'articles'));
		$this->redirect(array('action' => 'index'));
	}
	
	
/**
 *  add file
 */	
	public function add_file() {		
			
		if($this->FileUpload->success){
			if(isset($this->passedArgs['a']) && !empty($this->passedArgs['a'])) $this->redirect(array('controller'=>'articles','action' =>'view',$this->passedArgs['a']));				
		}else{
			$this->Session->setFlash($this->FileUpload->showErrors());
		}

		$data = array();
		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])){
			// dodajemy do domeny
			$this->Article->Domain->id = $this->passedArgs['d'];
			if ($this->Article->Domain->exists()) {
				$data['Upload']['domain_id'] = $this->passedArgs['d'];
			}else{
				$this->Session->setFlash(__('The article could not be saved. Please, select first domain'));
				$this->redirect($this->referer());
			}
			
			if(isset($this->passedArgs['a']) && !empty($this->passedArgs['a'])){
				// dodajemy do domeny
				$this->Article->id = $this->passedArgs['a'];
				if ($this->Article->exists()) {
					$data['Article']['id'] = $this->passedArgs['a'];
					$this->request->data = $data;
				}
			}
		}	

	}
	
/**
 * delete file
 */	
	public function delete_file($id = null){
		$this->autoRender = false;
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}

		$this->Article->Upload->id = $id;
		if (!$this->Article->Upload->exists()) {
			throw new NotFoundException(__('Invalid file'));
		}
		
		if(isset($this->passedArgs['a']) && !empty($this->passedArgs['a'])){
			// dodajemy do domeny
			$this->Article->id = $this->passedArgs['a'];
			if ($this->Article->exists()) {
				$data['Article']['id'] = $this->passedArgs['a'];
				$this->request->data = $data;
			}
		}
		
		$upload = $this->Article->Upload->findById($id);		
		
		$this->FileUpload->removeFile($upload['Upload']['name']);		
		if($this->Article->Upload->delete($id)){
			$this->Session->setFlash('Upload deleted');
			if(isset($this->passedArgs['a']) && !empty($this->passedArgs['a'])) $this->redirect(array('controller'=>'articles','action' =>'view',$this->passedArgs['a']));
			$this->redirect(array('action'=>'index'));
		}
		$this->redirect(array('action'=>'index'));
	}
	
}
